<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备编号" prop="innerCode">
        <el-input
            v-model="queryParams.innerCode"
            placeholder="请输入设备编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备容量" prop="channelMaxCapacity">
        <el-input
            v-model="queryParams.channelMaxCapacity"
            placeholder="请输入设备容量"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="点位Id" prop="nodeId">
        <el-input
            v-model="queryParams.nodeId"
            placeholder="请输入点位Id"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="addr">
        <el-input
            v-model="queryParams.addr"
            placeholder="请输入详细地址"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上次补货时间" prop="lastSupplyTime">
        <el-date-picker clearable
                        v-model="queryParams.lastSupplyTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择上次补货时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="区域Id" prop="regionId">
        <el-input
            v-model="queryParams.regionId"
            placeholder="请输入区域Id"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合作商Id" prop="partnerId">
        <el-input
            v-model="queryParams.partnerId"
            placeholder="请输入合作商Id"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备型号" prop="vmTypeId">
        <el-input
            v-model="queryParams.vmTypeId"
            placeholder="请输入设备型号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经度" prop="longitudes">
        <el-input
            v-model="queryParams.longitudes"
            placeholder="请输入经度"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维度" prop="latitude">
        <el-input
            v-model="queryParams.latitude"
            placeholder="请输入维度"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户端连接Id,做emq认证用" prop="clientId">
        <el-input
            v-model="queryParams.clientId"
            placeholder="请输入客户端连接Id,做emq认证用"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="策略id" prop="policyId">
        <el-input
            v-model="queryParams.policyId"
            placeholder="请输入策略id"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['manage:vm:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['manage:vm:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['manage:vm:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['manage:vm:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="vmList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键" align="center" prop="id"/>
      <el-table-column label="设备编号" align="center" prop="innerCode"/>
      <el-table-column label="设备容量" align="center" prop="channelMaxCapacity"/>
      <el-table-column label="点位Id" align="center" prop="nodeId"/>
      <el-table-column label="详细地址" align="center" prop="addr"/>
      <el-table-column label="上次补货时间" align="center" prop="lastSupplyTime" width="180">
        <template #default="scope">
          <span>{{
              parseTime(scope.row.lastSupplyTime,
                  '{y}-{m}-{d}')
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商圈类型" align="center" prop="businessType"/>
      <el-table-column label="区域Id" align="center" prop="regionId"/>
      <el-table-column label="合作商Id" align="center" prop="partnerId"/>
      <el-table-column label="设备型号" align="center" prop="vmTypeId"/>
      <el-table-column label="设备状态，0:未投放;1-运营;3-撤机" align="center" prop="vmStatus">
        <template #default="scope">
          <dict-tag :options="vm_status" :value="scope.row.vmStatus"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="运行状态" align="center" prop="runningStatus"/>
      <el-table-column label="经度" align="center" prop="longitudes"/>
      <el-table-column label="维度" align="center" prop="latitude"/>
      <el-table-column label="客户端连接Id,做emq认证用" align="center" prop="clientId"/>
      <el-table-column label="策略id" align="center" prop="policyId"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:vm:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['manage:vm:remove']">删除
          </el-button>
          <el-button link type="primary" icon="Info" @click="handleInfo(scope.row.id)"
                     v-hasPermi="['manage:vm:vmInfo']">设备详情
          </el-button>
          <el-button link type="primary" icon="Info" @click="handleInfo2(scope.row.id)"
                     v-hasPermi="['manage:vm:vmInfo']">设备详情2
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="vmRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编号" prop="innerCode">
          <el-input v-model="form.innerCode" placeholder="请输入设备编号"/>
        </el-form-item>
        <el-form-item label="设备容量" prop="channelMaxCapacity">
          <el-input v-model="form.channelMaxCapacity" placeholder="请输入设备容量"/>
        </el-form-item>
        <el-form-item label="点位" prop="nodeId">
          <el-select clearable v-model="form.nodeId" filterable placeholder="请输入点位Id">
            <el-option v-for="item in nodeList" :key="item.id" :label="item.nodeName" :value="item.id"/>
          </el-select>
          <!--          <el-input v-model="form.nodeId" placeholder="请输入点位Id"/>-->
        </el-form-item>
        <el-form-item label="详细地址" prop="addr">
          <el-input v-model="form.addr" placeholder="请输入详细地址"/>
        </el-form-item>
        <el-form-item label="上次补货时间" prop="lastSupplyTime">
          <el-date-picker clearable
                          v-model="form.lastSupplyTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择上次补货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="区域" prop="regionId">
          <!--          <el-input v-model="form.regionId" placeholder="请输入区域Id"/>-->
          <el-select clearable v-model="form.regionId" filterable placeholder="请输入区域Id">
            <el-option v-for="item in regionList" :key="item.id" :label="item.regionName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="合作商" prop="partnerId">
          <el-select clearable v-model="form.partnerId" filterable placeholder="请输入合作商Id">
            <el-option v-for="item in partnerList" :key="item.id" :label="item.partnerName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="商圈类型" prop="businessType">
          <el-select clearable v-model="form.businessType" filterable placeholder="请输入商圈类型">
            <el-option v-for="item in businessTypeList" :key="item.dictValue" :label="item.dictLabel"
                       :value="item.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号" prop="vmTypeId">
          <!--          <el-input v-model="form.vmTypeId" placeholder="请输入设备型号"/>-->
          <el-select clearable v-model="form.vmTypeId" filterable placeholder="请输入设备型号">
            <el-option v-for="item in vmTypeList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="经度" prop="longitudes">
          <el-input v-model="form.longitudes" placeholder="请输入经度"/>
        </el-form-item>
        <el-form-item label="维度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入维度"/>
        </el-form-item>
        <el-form-item label="客户端连接Id,做emq认证用" prop="clientId">
          <el-input v-model="form.clientId" placeholder="请输入客户端连接Id,做emq认证用"/>
        </el-form-item>
        <el-form-item label="策略" prop="policyId">
          <el-select clearable v-model="form.policyId" filterable placeholder="请输入策略id">
            <el-option v-for="item in policyList" :key="item.id" :label="item.policyName" :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="设备详情" v-model="vmInfoDetailVisible" width="850px" append-to-body>
      <div class="vmInfoDetail" v-loading="updateLoading">
        <span v-for="(row, rowIndex) in groupedData" :key="rowIndex">
        <div>
          <span style="border: 1px solid #eee;padding: 12px" v-for="(item, colIndex) in row" :key="colIndex">
          <div
              style="display: flex;flex-direction: column;align-items: center;justify-content: center;margin-top: 12px;">



          <el-select @change="updateCurVmItem(item)" v-model="item['商品']" clearable filterable
                     placeholder="请输入商品名称">
            <el-option v-for="sku in skuList" :key="sku.skuId" :label="sku.skuName" :value="sku['skuName']"/>
          </el-select>




            <span>货道: {{ item['货道'] }}</span>
            <span>货道: {{ item['channelId'] }}</span>


          </div>
        </span>
        </div>
      </span>
      </div>
      <div style="display: flex;align-items: center;justify-content: center">
        <el-button type="primary" @click="confirmHandler">提交确认</el-button>
        <el-button type="info" @click="cancelHandler">取消操作</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup name="Vm">
import {
  listVm,
  getVm,
  delVm,
  addVm,
  updateVm,
  getVmInfo,
  getVmWithChannelAndSkuInfo, editVmInfoById
} from "@/api/manage/vm";
import {listNode} from "@/api/manage/node.js";
import {globalVar} from "@/utils/generator/config.js";
import {listRegion} from "@/api/manage/region.js";
import {listPartner} from "@/api/manage/partner.js";
import {getDicts} from "@/api/system/dict/data.js";
import {listPolicy} from "@/api/manage/policy.js";
import {listVmType} from "@/api/manage/vmType.js";
import DictTag from "@/components/DictTag/index.vue";
import {listSku} from "@/api/manage/sku.js";
const {proxy} = getCurrentInstance();
const {vm_status} = proxy.useDict('vm_status');
const vmList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    innerCode: null,
    channelMaxCapacity: null,
    nodeId: null,
    addr: null,
    lastSupplyTime: null,
    businessType: null,
    regionId: null,
    partnerId: null,
    vmTypeId: null,
    vmStatus: null,
    runningStatus: null,
    longitudes: null,
    latitude: null,
    clientId: null,
    policyId: null,
  },
  rules: {
    nodeId: [
      {
        required: true,
        message: "点位Id不能为空",
        trigger: "blur"
      }
    ],
    lastSupplyTime: [
      {
        required: true,
        message: "上次补货时间不能为空",
        trigger: "blur"
      }
    ],
    businessType: [
      {
        required: true,
        message: "商圈类型不能为空",
        trigger: "change"
      }
    ],
    regionId: [
      {
        required: true,
        message: "区域Id不能为空",
        trigger: "blur"
      }
    ],
    partnerId: [
      {
        required: true,
        message: "合作商Id不能为空",
        trigger: "blur"
      }
    ],
    vmTypeId: [
      {
        required: true,
        message: "设备型号不能为空",
        trigger: "blur"
      }
    ],
    vmStatus: [
      {
        required: true,
        message: "设备状态，0:未投放;1-运营;3-撤机不能为空",
        trigger: "change"
      }
    ],
    createTime: [
      {
        required: true,
        message: "创建时间不能为空",
        trigger: "blur"
      }
    ],
  },
  nodeList: [],
  regionList: [],
  partnerList: [],
  vmTypeList: [],
  businessTypeList: [],
  policyList: []
});
const {
  queryParams,
  form,
  rules,
  nodeList,
  regionList,
  partnerList,
  vmTypeList,
  businessTypeList,
  policyList
} = toRefs(data);
onMounted(() => {
  //点位列表
  listNode({
    ...globalVar.page(),
  })
      .then(response => {
        nodeList.value = response.rows
      })
  //区域列表
  listRegion({
    ...globalVar.page(),
  })
      .then(response => {
        regionList.value = response.rows
      })
  //合作商列表
  listPartner({
    ...globalVar.page(),
  })
      .then(response => {
        partnerList.value = response.rows
      })
  //设备型号列表
  listVmType({
    ...globalVar.page(),
  })
      .then(response => {
        vmTypeList.value = response.rows
      })
  //
  listPolicy({
    ...globalVar.page(),
  })
      .then(response => {
        policyList.value = response.rows
      })
  //商圈类型
  getDicts("business_type")
      .then(response => {
        businessTypeList.value = response.data
      })
})
/** 查询设备列表 */
function getList() {
  loading.value = true;
  listVm(queryParams.value)
      .then(response => {
        vmList.value = response.rows;
        total.value = response.total;
        loading.value = false;
      });
}
//提交修改设备
const cancelHandler = () => {
}
const updateCurVmItem = (item) => {
  const index = curVm.value.detail.findIndex(detailItem => detailItem.货道 === `${item.row}-${item.col}`);
  if (index !== -1) {
    curVm.value.detail[index]['商品'] = item['商品'];
  }
}
let updateLoading = ref(false)
//修改设备
const confirmHandler = () => {
  updateLoading.value = true
  editVmInfoById(curVm.value).then((res) => {
    updateLoading.value = false
    proxy.$modal.msgSuccess(res.msg);
  })
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    innerCode: null,
    channelMaxCapacity: null,
    nodeId: null,
    addr: null,
    lastSupplyTime: null,
    businessType: null,
    regionId: null,
    partnerId: null,
    vmTypeId: null,
    vmStatus: null,
    runningStatus: null,
    longitudes: null,
    latitude: null,
    clientId: null,
    policyId: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("vmRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getVm(_id)
      .then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改设备";
      });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["vmRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateVm(form.value)
            .then(response => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            });
      } else {
        addVm(form.value)
            .then(response => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            });
      }
    }
  });
}
let curVm = ref(undefined)
let groupedData = ref([])
let vmInfoDetailVisible = ref(false)
let skuList = ref([])
onMounted(
    () => {
      listSku({
        ...globalVar.page(),
      }).then((res) => {
        skuList.value = res.rows
      })
    }
)
/*设备性情*/
const handleInfo = (id) => {
  vmInfoDetailVisible.value = true
  getVmInfo(id)
      .then((res) => {
        res.data.detail.forEach(item => {
          const [row, col] = item.货道.split('-').map(Number);
          if (!groupedData.value[row - 1]) {
            groupedData.value[row - 1] = [];
          }
          groupedData.value[row - 1][col - 1] = {
            ...item,
            row,
            col
          };
        });
        curVm.value = res.data
      })
}
const handleInfo2 = (id) => {
  getVmWithChannelAndSkuInfo(id)
      .then((res) => {
        console.log("res------------------>",
            res)
      })
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备编号为"' + _ids + '"的数据项？')
      .then(function () {
        return delVm(_ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => {
      });
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/vm/export',
      {
        ...queryParams.value
      },
      `vm_${new Date().getTime()}.xlsx`)
}
getList();
</script>
<style scoped lang="scss">
.vmInfoDetail {
  width: 100%;
  display: flex;
  flex-direction: column;
  & > span {
    display: flex;
    flex-direction: row;
    & > div {
      width: 100%;
      display: flex;
      & > span {
        flex: 1;
      }
    }
  }
}
</style>
